﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Optimization;
using george.Web;
namespace com.nm.library {
	public static class StylesHelper {
		const string KEY = "CSSP";
		static IList<BundlePacker> __packers;
		/// <summary>
		/// 把需要使用的CSS包添加到页面
		/// </summary>
		/// <param name="page">要添加的页面</param>
		/// <param name="packers">CSS包名称，可以多个，按顺序输出</param>
		/// <returns></returns>
		public static System.Web.UI.Page AddStylePacker(this System.Web.UI.Page page, params string[] packers) {
			if (page.Items[StylesHelper.KEY] == null) {
				page.Items[StylesHelper.KEY] = new List<string>();
			}
			var packerNameList = (List<string>)page.Items[StylesHelper.KEY];
			foreach (var str in packers) {
				if (packerNameList.Contains(str)) continue;
				var packer = getPacker(str);
				if (packer != null)
					packerNameList.Add(packer.Name);
			}
			return page;
		}
		/// <summary>
		/// 把需要使用的CSS包添加到页面
		/// </summary>
		/// <param name="page">要添加的页面</param>
		/// <param name="packers">CSS包名称，可以多个，按顺序输出</param>
		/// <returns></returns>
		public static System.Web.UI.Page AddStylePacker(this System.Web.UI.MasterPage page, params string[] packers) {
			return AddStylePacker(page.Page, packers);
		}
		/// <summary>
		/// 输出添加的CSS包
		/// </summary>
		/// <param name="page">页面</param>
		/// <returns></returns>
		public static IHtmlString GetStyles(this System.Web.UI.Page page) {
			var sb = new StringBuilder();
			//sb.Append(page.VirtualPath);
			var url = page.UniqueID;

			//sb.AppendLine(url);
			var bundlePath = url.Insert(0, "~/Content/").Replace("//", "/");
			//是否已经存在
			if (BundleManager.IsExists(bundlePath) == false) {
				var bundle = new StyleBundle(bundlePath);
				//是否添加了JS依赖包
				if (page.Items[StylesHelper.KEY] != null) {
					var packerNameList = (List<string>)page.Items[StylesHelper.KEY];
					if (packerNameList.Count > 0) {
						foreach (var name in packerNameList) {
							var packer = getPacker(name);
							if (packer != null) {
								bundle.Include(packer.Files.ToArray());
							}
						}
					}
				}
				//添加本页面JS
				//if (string.IsNullOrWhiteSpace(area)) {
				//	bundle.Include(String.Format("~/Scripts{0}.js", url));
				//} else {
				//	bundle.Include(String.Format("~/Scripts/Areas{0}.js", url));
				//}
				BundleManager.Add(bundle);
			}
			sb.Append(Styles.Render(bundlePath));
			var result = new HtmlString(sb.ToString());
			return result;
		}
		/// <summary>
		/// 输出添加的CSS包
		/// </summary>
		/// <param name="page">页面</param>
		/// <returns></returns>
		public static IHtmlString GetStyles(this System.Web.UI.MasterPage page) {
			return GetStyles(page.Page);
		}
		/// <summary>
		/// 输出CSS包
		/// </summary>
		/// <param name="page">页面</param>
		/// <param name="packers">要输出的包名，可以多个，按顺序输出</param>
		/// <returns></returns>
		/// <see cref="com.nm.library.BundleManager"/>
		public static IHtmlString GetStyles(this System.Web.UI.MasterPage page, params string[] packers) {
			return GetStyles(page.Page, packers);
		}
		/// <summary>
		/// 输出CSS包
		/// </summary>
		/// <param name="page">页面</param>
		/// <param name="packers">要输出的包名，可以多个，按顺序输出</param>
		/// <returns></returns>
		/// <see cref="com.nm.library.BundleManager"/>
		public static IHtmlString GetStyles(this System.Web.UI.Page page, params string[] packers) {
			var sb = new StringBuilder();
			//sb.Append(page.VirtualPath);
			var url = page.UniqueID + "/" +string.Join("-", packers);

			//sb.AppendLine(url);
			var bundlePath = url.Insert(0, "~/Content/").Replace("//", "/");
			//是否已经存在
			if (BundleManager.IsExists(bundlePath) == false) {
				var bundle = new StyleBundle(bundlePath);
				foreach (var name in packers) {
					var packer = getPacker(name);
					if (packer != null) {
						bundle.Include(packer.Files.ToArray());
					}
				}
				BundleManager.Add(bundle);
			}
			sb.Append(Styles.Render(bundlePath));
			var result = new HtmlString(sb.ToString());
			return result;
		}
		public static IHtmlString GetStyles(this System.Web.UI.MasterPage page, bool Optimization, params string[] packers) {
			return GetStyles(page.Page, Optimization, packers);
		}
		public static IHtmlString GetStyles(this System.Web.UI.Page page, bool Optimization, params string[] packers) {
			if (Optimization) {
				return StylesHelper.GetStyles(page, packers);
			}
			var sb = new StringBuilder();
			foreach (var name in packers) {
				var packer = getPacker(name);
				if (packer == null) continue;
				foreach (var cssUrl in packer.Files) {
					sb.Append(page.getStyleTag(cssUrl));
				}
			}
			var result = new HtmlString(sb.ToString());
			return result;
		}
		static BundlePacker getPacker(string name){
			return __packers == null 
				? null
                : __packers.FirstOrDefault(item => string.Compare(item.Name, name, StringComparison.Ordinal) == 0);
		}

		internal static void AddPacker(BundlePacker packer) {
			if (__packers == null) __packers = new List<BundlePacker>();
            var exists = __packers.Count(item => string.Compare(item.Name, packer.Name, StringComparison.Ordinal) == 0) > 0;
            if (exists) throw new ArgumentException(string.Format("{0} 已经存在", packer.Name));

			__packers.Add(packer);
		}
		public static IHtmlString Style(this System.Web.UI.MasterPage page, params string[] urls) {
			return Style(page.Page, urls);
		}
		public static IHtmlString Style(this System.Web.UI.Page page, params string[] urls) {
			var bundleDirectory = "~/bundles/" + BundleManager.MakeBundleName("css", urls);
			var bundle = BundleTable.Bundles.GetBundleFor(bundleDirectory);
			if (bundle != null) return Styles.Render(bundleDirectory);
			bundle = new StyleBundle(bundleDirectory).Include(urls);
			BundleTable.Bundles.Add(bundle);
			return Styles.Render(bundleDirectory);
		}
		public static IHtmlString Style(this System.Web.UI.MasterPage page, bool Optimization, params string[] urls) {
			return Style(page.Page, Optimization, urls);
		}
		public static IHtmlString Style(this System.Web.UI.Page page, bool Optimization, params string[] urls) {
			if (Optimization) {
				return StylesHelper.Style(page, urls);
			} else {
				var sb = new StringBuilder();
				foreach (var url in urls) {
					sb.Append(page.getStyleTag(url));
				}
				return new HtmlString(sb.ToString());
			}
		}
		static string getStyleTag(this System.Web.UI.Page page, string url) {
			return StylesHelper.getStyleTag(page.ResolveClientUrl(url), page.MapPath(url));
		}
		static string getStyleTag(string url, string fileName) {
			if (File.Exists(fileName) == false) return string.Empty;
			var ver = DateTime.Now.Ticks;
			if (myCache.Exists(url)) {
				ver = myCache.Get<long>(url);
			} else {
				var dp = new System.Web.Caching.CacheDependency(fileName);
				myCache.Insert(url, ver, dp);
			}
            return string.Format("<link href=\"{0}?v={1}\" rel=\"stylesheet\"/>", url, ver);
		}
	}//end class 
}//end namespace